// ✅ 插件功能说明
// 获取本机局域网 IP 地址（如 192.168.1.100）
// 获取 webpack-dev-server 启动的端口号
// 生成形如 http://192.168.1.100:8080 的 URL
// 使用 qrcode-terminal 在终端中输出二维码
const os = require("os");
const qrcode = require("qrcode-terminal");

const pluginName = "QrcodeWebpackPlugin";

function getLocalIP() {
  const interfaces = os.networkInterfaces();
  const availableIPList = [];

  for (const name of Object.keys(interfaces)) {
    for (const iface of interfaces[name]) {
      if (iface.family === "IPv4" && !iface.internal) {
        availableIPList.push(iface.address);
      }
    }
  }

  return availableIPList;
}

class QrcodeWebpackPlugin {
  constructor(options) {
    this.options = options || {
      small: true,
    };
  }

  apply(compiler) {
    compiler.hooks.afterEmit.tap(pluginName, (compiler) => {
      if (compiler.options.mode === "development") {
        const localIP = getLocalIP()[0];
        const { port: devServerPort, https } = compiler.options.devServer || {};
        const port = devServerPort || 8080;
        const protocol = https ? "https" : "http";
        const url = `${protocol}://${localIP}:${port}`;

        console.log(
          `\n Scan below QR code to open the url(${url}) on your phone:\n`
        );
        qrcode.generate(url, { small: !!this.options.small });
      }
    });
  }
}

module.exports = QrcodeWebpackPlugin;
